import React, { Component } from 'react'
import { Alert, Row, Col, Form, InputNumber, Button, Icon } from 'antd';
import { BasicLayoutSearch, BasicLayout } from '../../../components/BasicLayout';
import { TableCustomize, openModalMessage } from '../../../components/TableCustomize';
import QRCode from 'qrcode.react';
const FormItem = Form.Item;
const date = new Date();
const nowDate = date.toLocaleString();
export default class PickingTable extends Component {
    state = {
        acceptMap: [],
        batchNo: [],
        warehouseCode: [],
        batchNoStr: [],
        materialDat: [],
        batchNo11: [],
        acceptCode1: [],
        printData: {}
    }
    componentDidMount() {
        const { materialData, saveAcceptMap, takeNumber } = this.props
        const materialDat = materialData
        const acceptMap = []
        const acceptCode = []
        const batchNo = []
        const warehouseCode = []
        const takeNumber1 = []
        materialData.forEach((value, index) => {
            acceptMap.push(value.bodyVOList)
            acceptCode.push(value.acceptCode.split('-')[0])
            batchNo.push(value.batchNo)
            warehouseCode.push(value.warehouseCode)
            value.bodyVOList.forEach((value_1, index_1) => {
                takeNumber1.push(value_1.takeNumber)
            })
        })
        takeNumber(takeNumber1)
        const batchNo11 = Array.from(new Set(batchNo))
        const batchNoStr = batchNo11.map(item => item).join(',')
        const acceptCode1 = Array.from(new Set(acceptCode))
        this.setState({
            acceptMap,
            batchNo,
            warehouseCode,
            batchNoStr,
            materialDat,
            batchNo11,
            acceptCode1
        }, () => { saveAcceptMap(materialData) })

    }
    // 取消
    cancel = (a, i) => {
        const { materialDat, acceptCode, acceptMap } = this.state
        const { saveAcceptMap, takeNumber } = this.props
        let takeNum = []
        materialDat.forEach((value, index) => {
            value.bodyVOList.forEach((value_1, index_1) => {
                if (a.id === value_1.id) {
                    value.bodyVOList.splice(i, 1)
                }
                if (value.bodyVOList.length === 0) {
                    materialDat.splice(index, 1)
                }
            })
        })
        this.setState({
            materialDat
        })
        saveAcceptMap(this.state.materialDat)

        materialDat.forEach((value, index) => {
            value.bodyVOList.forEach((value_1, index_1) => {
                takeNum.push(value_1.takeNumber)
            })
        })
        takeNumber(takeNum)
    }
    onChange = (e, record) => {
        const takeNum = []
        record.takeNumber = e;
        const { saveAcceptMap, takeNumber } = this.props
        saveAcceptMap(this.state.materialDat)
        takeNum.push(takeNum)
        // console.log(takeNum);
        takeNumber(takeNum)
    }
    // 删除table
    closeBatchList = (index, item) => {
        const { acceptCode, materialDat } = this.state;
        materialDat.splice(index, 1);
        const { saveAcceptMap, takeNumber } = this.props;
        saveAcceptMap(materialDat)
        this.setState({ acceptCode, materialDat })
        let takeNum = []
        materialDat.forEach((value, index) => {
            value.bodyVOList.forEach((value_1, index_1) => {
                takeNum.push(value_1.takeNumber)
            })
        })
        takeNumber(takeNum)
    }
    // 发布欠料
    issue = (v) => {
        let id = [v.id]
        console.log(id);
        const { submit } = this.props
        submit(id)
    }
    // 提交欠料
    submit = (v, i) => {
        const data = []
        const { submit } = this.props

        v.bodyVOList.forEach((value, index) => {
            // console.log('3333', value);
            if (value.result === 0) {
                data.push(value.id)
            }
        })
        // console.log(data[0]);
        if (data[0] === undefined) {
            openModalMessage('warning', '当前领料单已完成！！');
            return
        }
        submit(data)
    }
    // 打印
    print = () => {
        openModalMessage('warning', '功能待开发！')
    }

    printQRCode = (index) => {
        this.changeImg(index, 'cardStyle' + index)

        setTimeout(() => {
            let html = document.getElementById('printQRCde' + index).innerHTML
            window.document.body.innerHTML = html
            window.print();
            window.location.reload();
        }, 1000)
    }


    canvasToImage = (canvas) => {
        var image = new Image();
        image.src = canvas.toDataURL("image/png");
        image.style = "width: 100%"
        return image;
    }
    changeImg = (index, id) => {
        var mycanvas = document.querySelectorAll(`#${id} canvas`);
        var img = this.canvasToImage(mycanvas[0]);
        var ewmImg = document.querySelector(`#${id} #ewm${index}`);
        ewmImg.parentNode.replaceChild(img, ewmImg)
    }
    render() {
        const { batchNo11, loading, acceptCode1, batchNo, warehouseCode, batchNoStr, materialDat } = this.state
        const { showConceal, ERPReturn } = this.props
        const columns = [
            {
                title: '序号',
                dataIndex: 'serialNumber',
                width: 50,
                align: 'center',
                render: (text, record, index) => `${index + 1}`,
            },
            {
                title: '物料编码',
                dataIndex: 'partCode',
                width: 100,
            },
            {
                title: '图号',
                dataIndex: 'paperCode',
                width: 180,
            },
            {
                title: '装配组别',
                dataIndex: 'category',
                width: 100,
            },
            {
                title: '物料名称',
                dataIndex: 'partName',
                width: 80,
            },
            {
                title: '物料规格',
                dataIndex: 'partSpec',
                width: 100,
            },
            {
                title: '仓库编码',
                dataIndex: 'storeCode',
                width: 100,
            },
            {
                title: '仓库名称',
                dataIndex: 'storeName',
                width: 100,
            },
            {
                title: '发放数量',
                dataIndex: 'takeNumber',
                width: 100,
                render: (text, record, index) =>
                    <div>
                        {
                            this.props.showConceal ? <span>{record.outNumber}</span> : <InputNumber min={0} onChange={(e) => this.onChange(e, record)} defaultValue={text}></InputNumber>
                        }
                    </div>,
            },
            {
                title: '需求数量',
                dataIndex: 'requestNumber',
                render: (text, record, index) =>
                    <div>
                        {
                            `${record.outNumber ? record.outNumber : ''}${record.outNumber ? '/' : ''}${text}`
                        }
                    </div>,
                width: 80,
            },
            {
                title: '结果',
                dataIndex: 'result',
                width: 100,
                render: (text, record, index) =>
                    <div>
                        {
                            text === 0 ? '库存不足' : text === 1 ? '成功' : null
                        }
                    </div>
            },
            {
                title: '操作',
                dataIndex: 'opes',
                width: 100,
                render: (text, record, index) =>
                    <div>
                        {
                            // 已发布欠料
                            this.props.showConceal ? (record.result === 0 ? <a onClick={this.issue.bind(this, record, index)}>{'发布欠料'}</a> : <a>--</a>) : <a onClick={this.cancel.bind(this, record, index)}>{'取消选择'}</a>
                        }
                    </div>

            },
            { dataIndex: '' }
        ]
        return (
            <div>
                <Row gutter={24}>
                    <Col span={8}>
                        <div>创建者：{localStorage.getItem('userName')}</div>
                        <div>创建时间：{nowDate}</div>
                    </Col>
                    <Col span={16}>
                        <Alert message={<div>已选择 <span style={{ color: '#1890ff' }}>{acceptCode1.length}</span> 张领料单，包括 <span style={{ color: '#1890ff' }}>{batchNo11.length}</span> 个批号<span>{batchNoStr}</span>，将被拆分 <span style={{ color: '#1890ff' }}>{warehouseCode ? warehouseCode.length : null}</span> 份出库单回传至ERP</div>} type="info" showIcon />
                    </Col>
                </Row>
                {
                    (ERPReturn !== null ? ERPReturn : materialDat).map((value, index) => {
                        return <BasicLayoutSearch key={index}>
                            <Form className="search-form" style={{ marginBottom: 10, position: 'relative' }}>
                                <Row gutter={24}>
                                    <Col span={4}>
                                        <FormItem label='批号:'>
                                            <span style={{ fontWeight: 'bold' }}>{value.batchNo}</span>
                                        </FormItem>
                                    </Col>
                                    <Col span={4}>
                                        <FormItem label='机型:'>
                                            <span style={{ fontWeight: 'bold' }}>{value.model}</span>
                                        </FormItem>
                                    </Col>
                                    <Col span={5}>
                                        <FormItem label='机位:'>
                                            <span style={{ fontWeight: 'bold' }}>{value.seatName}</span>
                                        </FormItem>
                                    </Col>
                                    <Col span={8}>
                                        <FormItem label='领料单:'>
                                            <span style={{ fontWeight: 'bold' }}>{value.acceptCode}</span>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <QRCode
                                    style={{ position: 'absolute', right: '130px', top: '0px' }}
                                    value={value.acceptCode}  //value参数为生成二维码的链接
                                    size={100} //二维码的宽高尺寸
                                    fgColor="#000000"  //二维码的颜色
                                />
                                <Row gutter={24}>
                                    <Col span={4}>
                                        <FormItem label='班组'>
                                            <span style={{ fontWeight: 'bold' }}>{value.groupName}</span>
                                        </FormItem>
                                    </Col>
                                    <Col span={4}>
                                        <FormItem label='车间'>
                                            <span style={{ fontWeight: 'bold' }}>{value.departName}</span>
                                        </FormItem>
                                    </Col>
                                    <Col span={5}>
                                        <FormItem label='总项数'>
                                            <span style={{ fontWeight: 'bold' }}>共{value.total}个</span>
                                        </FormItem>
                                    </Col>
                                    <Col span={8}>
                                        <FormItem label='出库单号'>
                                            <span style={{ fontWeight: 'bold' }}>{value.warehouseCode}</span>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <div className='closeIcon'><Icon type="close-circle" onClick={() => this.closeBatchList(index, value)} /></div>
                                <Button type='primary' style={{ position: 'absolute', top: 50, right: 0 }} onClick={() => this.printQRCode(index)} >打印</Button>
                            </Form>

                            <div id={'printQRCde' + index} style={{ display: 'none' }}>
                                <div id={'cardStyle' + index} style={{ width: '100%', padding: 10, fontSize: 12 }}>
                                    <div className="search-form" style={{ alignItems: 'center' }}>
                                        <div style={{ display: 'flex', }}>
                                            <div style={{ flex: 1 }}>
                                                <div>
                                                    <span>批号：{value.batchNo}</span>
                                                </div>
                                                <div>
                                                    <span>机型：{value.model}</span>
                                                </div>
                                                <div >
                                                    <span>机位：{value.seatName}</span>
                                                </div>
                                                <div >
                                                    <span>班组：{value.groupName}</span>
                                                </div>
                                                <div>
                                                    <span>车间：{value.departName}</span>
                                                </div>
                                                <div>
                                                    <span>总项数：共{value.total}个</span>
                                                </div>
                                            </div>
                                            <div style={{ width: 100 }}>
                                                <QRCode
                                                    style={{ display: 'none' }}
                                                    value={value.acceptCode}  //value参数为生成二维码的链接
                                                    size={100} //二维码的宽高尺寸
                                                    fgColor="#000000"  //二维码的颜色
                                                />
                                                <div className="codeImg" id={"ewm" + index}></div>
                                            </div>
                                        </div>
                                        <div style={{ display: 'flex' }}>
                                            <span>领料单：{value.acceptCode}</span>
                                        </div>
                                        <div style={{ display: 'flex' }}>
                                            <span>出库单号：{value.warehouseCode}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <TableCustomize
                                columns={columns}
                                rowKey={record => record.id}
                                dataSource={value.bodyVOList}
                                pagination={false}
                                scroll={{ y: 300 }}
                                rowClassName={(record, index) => {
                                    return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                                }}
                                footer={(record) => {
                                    let succeed = 0
                                    let takeNumber = 0
                                    let outNumber = 0
                                    let requestNumber = 0
                                    record.map(item => {
                                        if (item.result === 1) {
                                            succeed = Number(succeed) + 1
                                        }
                                        if (item.outNumber !== null) {
                                            outNumber += Number(item.outNumber)
                                        }
                                        takeNumber += Number(item.takeNumber)
                                        if (item.requestNumber !== null) {
                                            requestNumber += Number(item.requestNumber)
                                        }

                                    })
                                    return <div style={{ display: 'flex', }}>
                                        <div style={{ flexBasis: '68%' }}> 发放结果</div>
                                        <div style={{ flexBasis: '13%' }}>{value.resultTotalize}</div>
                                        <div style={{ flexBasis: '13%' }}>{value.totalize}</div>
                                    </div>
                                }}
                            />
                            {
                                showConceal ? <Row gutter={24} style={{ marginTop: '10px' }}>
                                    <Col span={3} style={{ display: 'flex', justifyContent: 'space-between', marginLeft: '300px', height: '32px', lineHeight: '32px' }}>
                                    </Col>
                                    <Col span={4}>
                                        <Button type='primary' onClick={this.submit.bind(this, value, index)}>提交欠料单</Button>
                                    </Col>
                                    <Col span={4}>
                                        <Button type='primary' onClick={this.print}>打印领料单</Button>
                                    </Col>
                                </Row> : null
                            }
                        </BasicLayoutSearch>
                    })
                }
            </div>
        )
    }
}
